<template>
  <div class="container">
    <h1 style="font-size: 22px">{{selectText}}列表</h1>
    <div>
      <a-dropdown>
        <a-menu slot="overlay" @click="handleMenuClick">
          <a-menu-item key="现有用户">现有用户 </a-menu-item>
          <a-menu-item key="待审核用户">待审核用户</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> {{selectText}} <a-icon type="down" /> </a-button>
      </a-dropdown>
    </div>
    <a-row>
      <a-col :span="20">
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="tableToExcel" style="margin-bottom: 15px; font-size: 18px">
          导出excel表
        </a-button>
      </a-col>
    </a-row>
    <a-table :data-source="data" :columns="columns" :rowKey="record => record.openid"
             @change="onChange">
      <div
        slot="filterDropdown"
        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        style="padding: 8px"
      >
        <a-input
          v-ant-ref="c => (searchInput = c)"
          :placeholder="`Search ${column.dataIndex}`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block;"
          @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        />
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          Search
        </a-button>
        <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
          Reset
        </a-button>
      </div>
      <a-icon
        slot="filterIcon"
        slot-scope="filtered"
        type="search"
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />

      <template slot="customRender" slot-scope="text, record, index, column">
        <span v-if="searchText && searchedColumn === column.dataIndex">
          <template
            v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <mark
              v-if="fragment.toLowerCase() === searchText.toLowerCase()"
              :key="i"
              class="highlight"
            >{{ fragment }}</mark
            >
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
        <template v-else>
          {{ text }}
        </template>
      </template>

      <template slot="operation" slot-scope="text, record">
        <div v-if="checkUser">
          <div style="display: inline">
            <a-popconfirm v-if="data.length" title="确定同意?" @confirm="() => checkChange(record.openid, 1)">
              <a-button type="primary" size = 'small' style="margin: 1px">
                同意
              </a-button>
            </a-popconfirm>
            <a-popconfirm v-if="data.length" title="确定拒绝?" @confirm="() => checkChange(record.openid, 0)">
              <a-button type="primary" size = 'small' style="margin: 1px">
                拒绝
              </a-button>
            </a-popconfirm>
          </div>
        </div>
        <div v-else>
          <div style="display: inline">
            <a-popconfirm v-if="data.length" title="确定更换权限?" @confirm="() => roleChange(record.openid)">
              <div v-if="!record.role"><a-icon type="arrow-up" style="font-size: 20px"/></div>
              <div v-else><a-icon type="arrow-down" style="font-size: 20px"/></div>
            </a-popconfirm>
            <a-popconfirm v-if="data.length" title="确定锁定或解锁?" @confirm="() => lockChange(record.openid)">
              <div v-if="record.isLock"><a-icon type="key" style="font-size: 20px"/></div>
              <div v-else><a-icon type="lock" style="font-size: 20px"/></div>
            </a-popconfirm>
          </div>
        </div>
      </template>

    </a-table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: [],
      saveData: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) =>
            record.name
              .toString()
              .includes(value),
          // 自动添加输入焦点
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          }
        },
        {
          title: '身份证',
          dataIndex: 'userId',
          key: 'userId',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) =>
            record.userId
              .toString()
              .includes(value),
          // 自动添加输入焦点
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          }
        },
        {
          title: '性别',
          dataIndex: 'sex',
          key: 'sex',
          customRender: function (text) {
            if (text === 1) {
              return '男'
            } else if (text === 2) {
              return '女'
            } else {
              return '未知'
            }
          },
          filters: [
            {
              text: '男',
              value: 1
            },
            {
              text: '女',
              value: 2
            }
          ],
          onFilter: (value, record) => record.sex === value
        },
        {
          title: '地址',
          dataIndex: 'address',
          key: 'address'
        },
        {
          title: '电话',
          dataIndex: 'phone',
          key: 'phone'
        },
        {
          title: '是否小区住户',
          dataIndex: 'isResident',
          key: 'isResident',
          customRender: function (text) {
            if (text === 0) {
              return '否'
            } else if (text === 1) {
              return '是'
            } else {
              return text
            }
          },
          filters: [
            {
              text: '否',
              value: 0
            },
            {
              text: '是',
              value: 1
            }
          ],
          onFilter: (value, record) => record.isResident === value
        },
        {
          title: '目前健康状态',
          dataIndex: 'status',
          key: 'status',
          customRender: function (text) {
            if (text === 0) {
              return '健康'
            } else if (text === 1) {
              return '预警'
            } else {
              return '高危'
            }
          },
          filters: [
            {
              text: '健康',
              value: 0
            },
            {
              text: '预警',
              value: 1
            },
            {
              text: '高危',
              value: 2
            }
          ],
          onFilter: (value, record) => record.status === value
        },

        {
          title: '账号类型',
          dataIndex: 'role',
          key: 'role',
          customRender: function (text) {
            if (text === 0) {
              return '普通用户'
            } else if (text === 1) {
              return '检查人员'
            } else {
              return text
            }
          },
          filters: [
            {
              text: '住户',
              value: 0
            },
            {
              text: '检查人员',
              value: 1
            }
          ],
          onFilter: (value, record) => record.role === value
        },
        {
          title: '是否锁定',
          dataIndex: 'isLock',
          key: 'isLock',
          customRender: function (text) {
            if (text === 0) {
              return '否'
            } else if (text === 1) {
              return '是'
            } else {
              return text
            }
          },
          filters: [
            {
              text: '否',
              value: 0
            },
            {
              text: '是',
              value: 1
            }
          ],
          onFilter: (value, record) => record.isLock === value
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      visible: false,
      selectText: '现有用户',
      checkUser: false
    }
  },
  created () {
    this.$http.get('/users')
      .then((resp) => {
        if (resp.body.status === 401) {
          this.$message.error('请先登录')
          this.$router.push('/login')
        } else {
          this.saveData = resp.body.data
          this.data = resp.body.data.filter(item => item.isVerify === 1)
        }
      }, (error) => {
        if (error.status === 401) {
          this.$message.error('请先登录')
          this.$router.push('/login')
        } else {
          this.$message.error('请保持网络通畅')
        }
      })
  },
  methods: {
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },

    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    roleChange (key) {
      console.log(key)
      this.$http.put('/user/role/' + key)
        .then((resp) => {
          if (resp.body.status === 200) {
            const newData = [...this.data]
            const target = newData.filter(item => item.openid === key)[0]
            if (target) {
              if (target.role) {
                target.role = 0
              } else {
                target.role = 1
              }
              this.data = newData
            }
            this.$message.success('此人权限已改变')
          } else {
            this.$message.error(resp.body.msg)
          }
        }, (error) => {
          console.log(error)
          this.$message.error('请保持网络畅通')
        })
    },
    lockChange (key) {
      this.$http.put('/user/lock/' + key)
        .then((resp) => {
          if (resp.body.status === 200) {
            const newData = [...this.data]
            const target = newData.filter(item => item.openid === key)[0]
            if (target) {
              if (target.isLock) {
                target.isLock = 0
              } else {
                target.isLock = 1
              }
              this.data = newData
            }
            this.$message.success('此账号锁定情况已改变')
          } else {
            this.$message.error(resp.body.msg)
          }
        }, (error) => {
          console.log(error)
          this.$message.error('请保持网络畅通')
        })
    },

    onChange (pagination, filters, sorter) {
      console.log('params', pagination, filters, sorter)
    },
    tableToExcel () {
      let str = '<tr><td>身份证</td><td>姓名</td><td>账号类型</td><td>性别</td><td>地址</td><td>电话</td><td>是否锁定</td><td>是否本地居民</td><td>健康状态</td></tr>'
      // 循环遍历，每行加入tr标签，每个单元格加td标签
      for (let i = 0; i < this.data.length; i++) {
        str += '<tr>'
        for (const item in this.data[i]) {
          // 增加\t为了不让表格显示科学计数法或者其他格式
          if (item === 'openid' || item === 'picture' || item === 'nick' || item === 'skey' || item === 'healthInfos') {
            continue
          }
          if (item === 'sex') {
            if (this.data[i][item] === 1) {
              str += '<td>男</td>'
            } else if (this.data[i][item] === 2) {
              str += '<td>女</td>'
            } else {
              str += '<td>未知</td>'
            }
          } else if (item === 'role') {
            if (this.data[i][item] === 0) {
              str += '<td>居民</td>'
            } else {
              str += '<td>检查人员</td>'
            }
          } else if (item === 'isLock' || item === 'isResident') {
            if (this.data[i][item] === 0) {
              str += '<td>否</td>'
            } else {
              str += '<td>是</td>'
            }
          } else if (item === 'status') {
            if (this.data[i][item] === 0) {
              str += '<td>健康</td>'
            } else if (this.data[i][item] === 1) {
              str += '<td>预警</td>'
            } else {
              str += '<td>高危</td>'
            }
          } else {
            str += `<td>${this.data[i][item] + '\t'}</td>`
          }
        }
        str += '</tr>'
      }
      // Worksheet名
      const worksheet = '用户信息表'
      const uri = 'data:application/vnd.ms-excel;base64,'

      // 下载的表格模板数据
      const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40" lang="en">
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`
      // 下载模板
      const link = document.createElement('a')
      link.href = uri + this.base64(template)
      // 对下载的文件命名
      link.download = '用户信息表.xls'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    base64 (s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    },
    handleMenuClick ({ key }) {
      if (key === '现有用户') {
        const newData = [...this.saveData]
        this.data = newData.filter(item => item.isVerify === 1)
        this.checkUser = false
      } else {
        const newData = [...this.saveData]
        this.data = newData.filter(item => item.isVerify === 0)
        console.log(this.data)
        this.checkUser = true
      }
      this.selectText = key
    },
    checkChange (openid, checked) {
      this.$http.put('/user/check', { openid: openid, checked: checked }, { emulateJSON: true })
        .then((resp) => {
          if (resp.body.status === 200) {
            const newData = [...this.data]
            this.data = newData.filter(item => item.openid !== openid)
            const newSaveData = [...this.saveData]
            if (checked === 1) {
              const target = newSaveData.filter(item => item.openid === openid)[0]
              if (target) {
                target.isVerify = 1
                this.saveData = newSaveData
              }
            } else {
              this.saveData = newSaveData.filter(item => item.openid !== openid)
            }
            this.$message.success('已处理该申请')
          } else {
            this.$message.error(resp.body.msg)
          }
        }, (error) => {
          console.log(error)
          this.$message.error('请保持网络畅通')
        })
    }
  }
}
</script>
<style scoped>
  .highlight {
    background-color: rgb(255, 192, 105);
    padding: 0;
  }
  .container{
  }
</style>
